<route lang="yaml">
meta:
  enabled: false
          </route>

<script lang="ts" setup>
import { VXETable } from 'vxe-table'
import type { VxeFormEvents, VxeFormInstance, VxePagerEvents, VxeSelectEvents, VxeTableInstance } from 'vxe-table'
import { ElMessage } from 'element-plus'
import apiRoute from '@/api/modules/route'
import apiCarrier from '@/api/modules/carrier'
import apiCar from '@/api/modules/car'
import apiDriver from '@/api/modules/driver'

const refModalForm = ref<VxeFormInstance>()
const pageData = reactive({
  loading: false,
  tableData: [] as any[],
  // 弹窗相关
  modalShow: false,
  modalName: '',
  carrierList: [] as any[],
  carList: [] as any[],
  driverList: [] as any[],
})
const tablePage = reactive({
  total: 0,
  currentPage: 1,
  pageSize: 10,
})
interface ModalForm {
  id: number
  name: string
  code: string
  carrier_name: string
  carrier_id: string
  car_sn: string
  car_id: string
  driver_name: string
  driver_id: string
}
const modalFormData = ref<ModalForm>({
  id: 0,
  name: '',
  code: '',
  carrier_name: '',
  carrier_id: '',
  car_sn: '',
  car_id: '',
  driver_name: '',
  driver_id: '',
})
const formRules = {
  sn: [
    { required: true, message: '请输入名称' },
  ],
}
interface FormDataVO {
  name: string
}
const formTop = reactive<FormDataVO>({
  name: '',
})
function sumbitModalEvent() {
  refModalForm.value?.validate((valid) => {
    if (!valid) { // 校验通过
      apiRoute.createOrUpdate(modalFormData.value).then((res: any) => {
        pageData.modalShow = false
        // tablePage.currentPage = 1
        // tablePage.pageSize = 10
        const req = {
          pageIndex: tablePage.currentPage,
          pageSize: tablePage.pageSize,
          name: formTop.name,
        }
        apiPage(req)
      }).catch((e: any) => {
        if (e.msg) {
          ElMessage.error({
            message: e.msg,
            center: true,
          })
        }
      })
    }
  })
}
function cancelModalEvent() {
  pageData.modalShow = false
}
const tableRef = ref<VxeTableInstance>()
/// ///////////////////////////////////右侧按钮相关
function delItem(row: any) {
  VXETable.modal.confirm('确定删除？').then((res) => {
    if (res === 'confirm') {
      apiRoute.del(row.id).then((res: any) => {
        const $table = tableRef.value
        $table?.remove(row)
      })
    }
  })
}
function editItem(row: any) {
  pageData.modalName = '编辑'
  modalFormData.value = row
  pageData.modalShow = true
}
/// ///////////////////////////////////top按钮相关
function newOrg() {
  pageData.modalName = '新增'
  modalFormData.value = {} as any
  pageData.modalShow = true
}
function removeSelected() {
  const $table = tableRef.value
  if ($table?.getCheckboxRecords().length === 0) {
    ElMessage.error({
      message: '请选中删除行',
      center: true,
    })
    return
  }
  VXETable.modal.confirm('确定删除！！！').then((res) => {
    if (res === 'confirm') {
      const ids = $table?.getCheckboxRecords().map(item => item.id)
      apiRoute.delBatch(ids).then((res: any) => {
        $table?.removeCheckboxRow()
      })
    }
  })
}
function manualSync() {
  apiRoute.syncInfo({}).then((res) => {
    ElMessage.success({
      message: '开始同步',
      center: true,
    })
  }).catch((e) => {
    if (e && e.msg) {
      ElMessage.error({
        message: e.msg,
        center: true,
      })
    }
  })
}
/// ///////////////////////////////////api
function apiPage(req: any) {
  pageData.loading = true
  apiRoute.page(req).then((res) => {
    pageData.tableData = res.data.list
    tablePage.total = res.data.total
    pageData.loading = false
  }).catch((err) => {
    ElMessage.error({
      message: JSON.stringify(err),
      center: true,
    })
    pageData.loading = false
  })
}
function apiListCarrier() {
  apiCarrier.list({}).then((res: any) => {
    pageData.carrierList = res.data.list
  })
}
function apiListCar() {
  apiCar.list({}).then((res: any) => {
    pageData.carList = res.data.list
  })
}
function apiListDriver() {
  apiDriver.list({}).then((res: any) => {
    pageData.driverList = res.data.list
  })
}
/// ////////////////////////////////////下拉
const carrierSelectChange: VxeSelectEvents.Change = (e) => {
  for (let i = 0; i < pageData.carrierList.length; i++) {
    if (pageData.carrierList[i].id === e.value) {
      modalFormData.value.carrier_name = pageData.carrierList[i].name
      break
    }
  }
}
const carSelectChange: VxeSelectEvents.Change = (e) => {
  for (let i = 0; i < pageData.carList.length; i++) {
    if (pageData.carList[i].id === e.value) {
      modalFormData.value.car_sn = pageData.carList[i].sn
      break
    }
  }
}
const driverSelectChange: VxeSelectEvents.Change = (e) => {
  for (let i = 0; i < pageData.driverList.length; i++) {
    if (pageData.driverList[i].id === e.value) {
      modalFormData.value.driver_name = pageData.driverList[i].name
      break
    }
  }
}
/// ///////////////////////////////////翻页
const submitTopEvent: VxeFormEvents.Submit = () => {
  tablePage.currentPage = 1
  tablePage.pageSize = 10
  const req = {
    pageIndex: tablePage.currentPage,
    pageSize: tablePage.pageSize,
    name: formTop.name,
  }
  apiPage(req)
}

const resetTopEvent: VxeFormEvents.Reset = () => {
  tablePage.currentPage = 1
  tablePage.pageSize = 10
  const req = {
    pageIndex: tablePage.currentPage,
    pageSize: tablePage.pageSize,
    name: formTop.name,
  }
  // console.log(req)
  apiPage(req)
}
const handlePageChange: VxePagerEvents.PageChange = ({ currentPage, pageSize }) => {
  tablePage.currentPage = currentPage
  tablePage.pageSize = pageSize
  const req = {
    pageIndex: tablePage.currentPage,
    pageSize: tablePage.pageSize,
    name: formTop.name,
  }
  apiPage(req)
}
/// ///////////////////////////////////生命周期
onMounted(() => {
  tablePage.currentPage = 1
  tablePage.pageSize = 10
  const req = {
    pageIndex: tablePage.currentPage,
    pageSize: tablePage.pageSize,
    name: formTop.name,
  }
  apiPage(req)
  apiListCarrier()
  apiListCar()
  apiListDriver()
})
</script>

<template>
  <div class="page-wrap">
    <div class="page-top">
      <vxe-form :data="formTop" style="padding-left: 5px;" @submit="submitTopEvent" @reset="resetTopEvent">
        <vxe-form-item title="名称" field="name" :item-render="{}">
          <template #default="{ data }">
            <vxe-input v-model="data.name" placeholder="请输入名称" clearable />
          </template>
        </vxe-form-item>
        <vxe-form-item>
          <template #default>
            <vxe-button type="submit" status="primary" content="搜索" />
            <vxe-button type="reset" content="重置" />
          </template>
        </vxe-form-item>
      </vxe-form>
      <vxe-toolbar>
        <template #buttons>
          <vxe-button style="margin-left: 5px;" @click="newOrg">
            新增
          </vxe-button>
          <vxe-button @click="removeSelected">
            删除选中
          </vxe-button>
          <vxe-button @click="manualSync">
            手动同步
          </vxe-button>
        </template>
      </vxe-toolbar>
    </div>
    <page-main>
      <vxe-table
        ref="tableRef" auto-resize border stripe :loading="pageData.loading" :column-config="{ resizable: true }"
        :row-config="{ isHover: true }" :checkbox-config="{ highlight: true, range: true }" :data="pageData.tableData"
        align="center" header-align="center"
      >
        <vxe-column type="checkbox" width="50" />
        <vxe-column field="name" align="center" title="名称" />
        <vxe-column field="code" align="center" title="编码" />
        <vxe-column field="carrier_name" align="center" title="承运商" />
        <vxe-column field="car_sn" align="center" title="车辆" />
        <vxe-column field="driver_name" align="center" title="司机" />
        <vxe-column title="操作" fixed="right" width="200">
          <template #default="{ row }">
            <vxe-button type="text" @click="editItem(row)">
              编辑
            </vxe-button>
            <vxe-button type="text" @click="delItem(row)">
              删除
            </vxe-button>
          </template>
        </vxe-column>
      </vxe-table>
    </page-main>
    <div class="page-opration-container">
      <vxe-pager
        v-model:current-page="tablePage.currentPage" v-model:page-size="tablePage.pageSize"
        :layouts="['Sizes', 'PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'FullJump', 'Total']"
        :total="tablePage.total" @page-change="handlePageChange"
      />
    </div>
    <div>
      <vxe-modal v-model="pageData.modalShow" width="800" height="600">
        <template #title>
          <span style="color: red;">{{ pageData.modalName }}</span>
        </template>
        <template #default>
          <div style="display: flex;flex-direction: column;height: 100%;">
            <div style="flex: 1;">
              <vxe-form ref="refModalForm" :data="modalFormData" :rules="formRules" title-width="80">
                <vxe-form-gather span="24">
                  <vxe-form-item title="名称" field="name" :item-render="{}" span="12">
                    <template #default="{ data }">
                      <vxe-input v-model="data.name" placeholder="请输入名称" clearable />
                    </template>
                  </vxe-form-item>
                  <vxe-form-item title="编码" field="code" :item-render="{}" span="12">
                    <template #default="{ data }">
                      <vxe-input v-model="data.code" placeholder="请输入编码" clearable />
                    </template>
                  </vxe-form-item>
                </vxe-form-gather>
                <vxe-form-gather span="24">
                  <vxe-form-item title="承运商" field="carrier_id" :item-render="{}" span="12">
                    <template #default="{ data }">
                      <vxe-select v-model="data.carrier_id" placeholder="请选择承运商" clearable @change="carrierSelectChange">
                        <vxe-option v-for="(item, index) in pageData.carrierList" :key="index" :value="item.id" :label="item.name" />
                      </vxe-select>
                    </template>
                  </vxe-form-item>
                  <vxe-form-item title="车辆" field="car_id" :item-render="{}" span="12">
                    <template #default="{ data }">
                      <vxe-select v-model="data.car_id" placeholder="请选择车辆" clearable @change="carSelectChange">
                        <vxe-option v-for="(item, index) in pageData.carList" :key="index" :value="item.id" :label="item.sn" />
                      </vxe-select>
                    </template>
                  </vxe-form-item>
                </vxe-form-gather>
                <vxe-form-gather span="24">
                  <vxe-form-item title="司机" field="driver_id" :item-render="{}" span="12">
                    <template #default="{ data }">
                      <vxe-select v-model="data.driver_id" placeholder="请选择司机" clearable @change="driverSelectChange">
                        <vxe-option v-for="(item, index) in pageData.driverList" :key="index" :value="item.id" :label="item.name" />
                      </vxe-select>
                    </template>
                  </vxe-form-item>
                </vxe-form-gather>
              </vxe-form>
            </div>

            <div style="display: flex;justify-content: flex-end;">
              <vxe-button content="取消" @click="cancelModalEvent" />
              <vxe-button status="primary" content="提交" @click="sumbitModalEvent" />
            </div>
          </div>
        </template>
      </vxe-modal>
    </div>
  </div>
</template>

    <style lang="scss" scoped>
    .page-wrap {
      position: absolute;
      width: 100%;
      height: 100%;
      display: flex;
      flex-direction: column;

      .page-top {
        margin-top: 5px;
        padding-left: 20px;
        padding-right: 20px;
      }

      .page-main {
        flex: 1;
        overflow: auto;
        margin-bottom: 5px;
        margin-top: 5px;
        padding-top: 5px;
      }

      .page-opration-container {
        display: flex;
        justify-content: center;
        align-items: center;
        padding-bottom: 5px;
      }
    }
    </style>
